'''
    Sky Access (skyaccess.se) XBMC Plugin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.		
'''

import os
import string
import sys
import re
import xbmcvfs
import xbmc, xbmcaddon, xbmcplugin, xbmcgui
import datetime
import time

from t0mm0.common.addon import Addon
from t0mm0.common.net import Net

addon_id = 'plugin.video.skyaccess.se'

BASEURL = 'http://skyaccess.se/'
ELITEURL = 'http'
#http://skyaccess.se/Login/

addon = Addon(addon_id, sys.argv)
userdata_path = addon.get_profile()

def make_dir(mypath, dirname):
    ''' Creates sub-directories if they are not found. '''
    subpath = os.path.join(mypath, dirname)
    if not xbmcvfs.exists(subpath): 
        try:
            xbmcvfs.mkdirs(subpath)
        except:
            xbmcvfs.mkdir(subpath)
    return subpath
make_dir(userdata_path, '')

username = addon.addon.getSetting('username')
password = addon.addon.getSetting('password')
accinfo = addon.addon.getSetting('account_info')

if username=='':
    dialog = xbmcgui.Dialog()
    dialog.ok("Sky Access", "You Now Need To Input Your [COLOR yellow]Sky Access Username[/COLOR].")
    keyboard = xbmc.Keyboard(username, 'Sky Access Username')
    keyboard.doModal()
    if keyboard.isConfirmed():
        username = keyboard.getText() 
    addon.addon.setSetting('username',username)
    time.sleep(1)
    
if password=='':
    dialog = xbmcgui.Dialog()
    dialog.ok("Sky Access", "You Now Need To Input Your [COLOR yellow]Sky Access Password[/COLOR].")
    keyboard = xbmc.Keyboard(password, 'Sky Access Password')
    keyboard.doModal()
    if keyboard.isConfirmed():
        password = keyboard.getText() 
    addon.addon.setSetting('password',password)
    time.sleep(1)

cookie_file = os.path.join(userdata_path, '1.lwp')
net = Net(cookie_file=cookie_file)

mode = addon.queries['mode']
url = addon.queries.get('url', '')
title = addon.queries.get('title', '')
img = addon.queries.get('img', '')

try:
    if accinfo != username+password:
        os.remove(cookie_file)
        addon.addon.setSetting('account_info',accinfo)
except: 
    pass


def escape(text):
        try:            
            rep = {" ": "%20"                  
                   }
            for s, r in rep.items():
                text = text.replace(s, r)

        except TypeError:
            pass

        return text
    
def unescape(text):
        try:            
            rep = {"&nbsp;": " ",
                   "\n": "",
                   "\t": "",                   
                   }
            for s, r in rep.items():
                text = text.replace(s, r)
				
            # remove html comments
            text = re.sub(r"<!--.+?-->", "", text)    
				
        except TypeError:
            pass

        return text
		
def MainMenu():  #home-page
        
    url = BASEURL + 'Login/'
    html = net.http_POST(url, {'username':username, 'password':password, 'submit':'Log in', 'action':'do_login'}).content
    
    for item in re.finditer(r"<a class=\"link\" href=\"(.+?)\".+?>(.+?) Streams</a>", html):
        item_url = item.group(1)        
        item_title = item.group(2)
        if 'iframead' in item_url:
            html_1 = net.http_GET(item_url).content      
            item_url = re.compile('<li><a href="(.+?)">').findall(html_1)[0]
        
        item_title = item_title + ' Content'
        
        addon.add_directory({'mode':'menu', 'url':item_url, 'title':item_title}, {'title':  item_title})
        
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
    
def Menu():
    temp_url = url
    if temp_url.rfind("/") == len(temp_url)-1:
        temp_url = temp_url[:len(temp_url)-1]
    
    url_last_part = temp_url[temp_url.rfind("/"):]
    
    premium_user = False
    html = net.http_GET(url).content

    if "Member Login" in html:
        login_url = 'http://hostaccess.org/amember/login'
        data = {}
        data['amember_login'] = username
        data['amember_pass'] = password
        hidden_inputs = re.findall(r'type="hidden" name="(.+?)" value="(.+?)"', html)
        for name, value in hidden_inputs:
            data[name] = value

        html = net.http_POST(login_url, data).content
        item_url = re.search('<meta http-equiv="refresh" content="0;url=(.+?)" />', html)
        if item_url:
            html = net.http_GET(item_url.group(1)).content
        net.save_cookies(cookie_file)
        
    if 'Access Denied' in html:
        dialog = xbmcgui.Dialog()
        dialog.ok("Sky Access", "Access Denied. [COLOR yellow]Please subscribe[/COLOR].")
        return
    
    stream = re.search("(?s)(<embed.+?src.+?swf.+?flashvars.+?streamer.+?>)", html)
    if stream:
        stream = stream.group(1)
        
        pageurl = url
        swfurl = re.compile("src=[\"'](.+?)[\"']").findall(stream)[0]
        streamer = re.compile('streamer=(.+?)&').findall(stream)[0]
        playpath = re.compile('file=(.+?)&').findall(stream)[0]
        
        if '.mp4' in playpath:
            playpath = 'mp4:' + playpath
        elif playpath.endswith('.flv'):
            playpath = playpath[:-4]
        
        stream_path = streamer + ' playpath=' + playpath + ' pageUrl=' + pageurl + ' swfUrl=' + swfurl + ' timeout=30'        
        
        if 'vod' not in streamer:
            stream_path = stream_path + ' live=true'
            
        print stream_path
            
        addon.log(stream_path)
        
        listitem = xbmcgui.ListItem()
        listitem.setInfo('video', {'Title': title} )       
        xbmc.Player().play(stream_path, listitem)

    else:
        item_re = r"<li>.*?<a href=\"(.+?)\">(.+?)</li>"
        
        for item in re.finditer(item_re, html):
            
            item_url = item.group(1)
            
            item_title = item.group(2)
            item_title = re.sub("<.+?>", "", item_title)
            if 'BACK' in item_title or 'Donate' in item_title:
                continue
            
            item_img = ''
            if 'HOSTACCESS' in url:
                #item_img = url + item_title  
                print item_img
                if 'elitemenu' in item_url:
                    item_title = 'Elite Streams'
                elif 'replays' in item_url:
                    item_title = 'On Demand'
            
            if 'http' not in item_url:
                item_url = BASEURL + item_url
                       
            addon.add_directory({'mode':'menu', 'url':item_url, 'title':item_title}, {'title':  item_title})
            
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
    
if mode == 'main': 
    MainMenu()
elif mode == 'menu':
    Menu()